package com.raidpoints.client;

import java.io.Serializable;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import net.zschech.gwt.comet.client.CometClient;
import net.zschech.gwt.comet.client.CometSerializer;
import net.zschech.gwt.comet.client.CometListener;
import net.zschech.gwt.comet.client.SerialTypes;

import com.bradrydzewski.gwt.calendar.client.Appointment;
import com.bradrydzewski.gwt.calendar.client.AppointmentStyle;
import com.bradrydzewski.gwt.calendar.client.Calendar;
import com.bradrydzewski.gwt.calendar.client.CalendarSettings;
import com.bradrydzewski.gwt.calendar.client.CalendarViews;
import com.bradrydzewski.gwt.calendar.client.event.TimeBlockClickEvent;
import com.bradrydzewski.gwt.calendar.client.event.TimeBlockClickHandler;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.EventHandler;
import com.google.gwt.event.shared.GwtEvent;
import com.google.gwt.event.shared.HasHandlers;
import com.google.gwt.i18n.client.TimeZone;
import com.google.gwt.user.cellview.client.CellTree;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.DeferredCommand;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.Event.NativePreviewEvent;
import com.google.gwt.user.client.Event.NativePreviewHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.rpc.ServiceDefTarget;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DockLayoutPanel;
import com.google.gwt.user.client.ui.Frame;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootLayoutPanel;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.TabLayoutPanel;
import com.google.gwt.user.client.ui.Tree;
import com.google.gwt.user.client.ui.TreeItem;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.ListDataProvider;



public class RaidPoints implements EntryPoint {
	
	RootLayoutPanel rP;
	DockLayoutPanel mP;
	TreeItem eventItem;
	TreeItem pointsItem;
	TreeItem accountItem;
	TreeItem groupItem;
	TabLayoutPanel tPanel;
	Label loginLabel;
	AuthType auth;
	AuthType prevauth;
	RaidPointsServiceAsync rpsvc;
	AsyncCallback<String> authCallback;	
	AsyncCallback<String> destCallback;
	AsyncCallback<String> stringCallback;
	AsyncCallback<String> alertCallback;
	AsyncCallback<Integer> offsetCallback;
	AsyncCallback<ArrayList<String>> pollCallback;
	Label helpLabel;
	boolean ctrldown;
	RaidPoints mrp;
    HashMap<String,ArrayList<String>> destlist;
    HashMap<TreeItem,Widget> navmap;
    HashMap<Widget, TreeItem> renavmap;
    HashMap<String, TreeItem> idmap;
    ArrayList<PointsPage> pointspagelist;
    ArrayList<CharacterPointsTable> charpagelist;
    ArrayList<AccountPage> accountlist;
    ListDataProvider<event> dataProvider;
    Tree navtree;
    String uname;
    int uid;
    int timeos;
    TimeZone pacTime;
    int idcount;
    Comparator<event> tsComp;
    boolean jli;
    boolean updatehist;
    boolean firstload;
    String lasthist;
    CometClient cometClient;
    boolean polllock;
    int mpointer;
    int permtabs;
    int calheight;
    int starttab;
    Widget helpWidget;
    boolean mil;
    ArrayList<String> tablist;
    int currtab;
    VerticalPanel sideTabPan;
	private DockLayoutPanel westPanel;
    
    @SerialTypes({String.class})
    public static abstract class ChatCometSerializer extends CometSerializer {
    }

    
 public void onModuleLoad() {
	 mrp = this;
	 auth = AuthType.noauth;
	 ctrldown = false;
	 destlist = null;
	 helpWidget = null;
	 updatehist = false;
	 firstload = true;
	 uname = "";
	 starttab = -1;
	 timeos = 0;
	 jli = false;
	 uid = -1;
	 mpointer = -2;
	 idcount = 0;
	 mil = true;
	 polllock = false;
	 calheight = 0;
	 currtab = 0;
	 sideTabPan = new VerticalPanel();
	 tablist = new ArrayList<String>();
	 navmap = new HashMap<TreeItem,Widget>();
	 renavmap = new HashMap<Widget,TreeItem>();
	 pointspagelist = new ArrayList<PointsPage>();
	 charpagelist = new ArrayList<CharacterPointsTable>();
	 accountlist = new ArrayList<AccountPage>();
	 idmap = new HashMap<String,TreeItem>();
	 dataProvider = new ListDataProvider<event>();
	 lasthist = History.getToken();
	 
	// pacTime = TimeZone.createTimeZone("\"transitions\": [2770, 60, 7137, 0, 11506, 60, 16041, 0, 20410, 60, 24777, 0, 29146, 60, 33513, 0, 35194, 60, 42249, 0, 45106, 60, 50985, 0, 55354, 60, 59889, 0, 64090, 60, 68625, 0, 72994, 60, 77361, 0, 81730, 60, 86097, 0, 90466, 60, 94833, 0, 99202, 60, 103569, 0, 107938, 60, 112473, 0, 116674, 60, 121209, 0, 125578, 60, 129945, 0, 134314, 60, 138681, 0, 143050, 60, 147417, 0, 151282, 60, 156153, 0, 160018, 60, 165057, 0, 168754, 60, 173793, 0, 177490, 60, 182529, 0, 186394, 60, 191265, 0, 195130, 60, 200001, 0, 203866, 60, 208905, 0, 212602, 60, 217641, 0, 221338, 60, 226377, 0, 230242, 60, 235113, 0, 238978, 60, 243849, 0, 247714, 60, 252585, 0, 256450, 60, 261489, 0, 265186, 60, 270225, 0, 273922, 60, 278961, 0, 282826, 60, 287697, 0, 291562, 60, 296433, 0, 300298, 60, 305337, 0, 309034, 60, 314073, 0, 317770, 60, 322809, 0, 326002, 60, 331713, 0, 334738, 60, 340449, 0, 343474, 60, 349185, 0, 352378, 60, 358089, 0, 361114, 60, 366825, 0, 369850, 60, 375561, 0, 378586, 60, 384297, 0, 387322, 60, 393033, 0, 396058, 60, 401769, 0, 404962, 60, 410673, 0, 413698, 60, 419409, 0, 422434, 60, 428145, 0, 431170, 60, 436881, 0, 439906, 60, 445617, 0, 448810, 60, 454521, 0, 457546, 60, 463257, 0, 466282, 60, 471993, 0, 475018, 60, 480729, 0, 483754, 60, 489465, 0, 492490, 60, 498201, 0, 501394, 60, 507105, 0, 510130, 60, 515841, 0, 518866, 60, 524577, 0, 527602, 60, 533313, 0, 536338, 60, 542049, 0, 545242, 60, 550953, 0, 553978, 60, 559689, 0, 562714, 60, 568425, 0, 571450, 60, 577161, 0, 580186, 60, 585897, 0, 588922, 60, 594633, 0], \"names\": [\"PST\", \"Pacific Standard Time\", \"PDT\", \"Pacific Daylight Time\"], \"id\": \"America/Los_Angeles\", \"std_offset\": -480}");
	 pacTime = TimeZone.createTimeZone(360);

	 rpsvc = GWT.create(RaidPointsService.class);
	 ServiceDefTarget serviceDefTarget = (ServiceDefTarget) rpsvc;
	 serviceDefTarget.setServiceEntryPoint("servlet/rpsvc");
	 
	 SetupCallbacks();
	 
	 mP = new DockLayoutPanel(Unit.EM);
	 rP = RootLayoutPanel.get();
	 rP.add(mP);
	 
	 HTML banner = new HTML("Night Watch Raid Points");
	 banner.setStyleName("banner");
	 mP.addNorth(banner,3);
	 
	 Event.addNativePreviewHandler(new NativePreviewHandler(){
			@Override
			public void onPreviewNativeEvent(NativePreviewEvent event) {
				//if(!event.getNativeEvent().getType().equals("keypress")) return;
				ctrldown = event.getNativeEvent().getCtrlKey();	
				}
		}); 

	 
	 
	 navtree = new Tree(){
			public void onBrowserEvent(Event e) { {
				sinkEvents(Event.ONDBLCLICK);
			}
			super.onBrowserEvent(e);
			if(DOM.eventGetType(e) == Event.ONDBLCLICK) {
				TreeItem sitem = navtree.getSelectedItem();
				if(sitem.getParentItem() != null){
					RemoveTab(sitem);
				}

			}
			}
		}; 
		
		 eventItem = new TreeItem("<font size=\"4\">Raid List</font>");
		 pointsItem = new TreeItem("<font size=\"4\">Points List</font>");
		 accountItem = new TreeItem("<font size=\"4\">My Account</font>");
		 groupItem = new TreeItem("<font size=\"4\">Groups</font>");
		
		 navtree.addItem(accountItem);
		 navtree.addItem(eventItem);
		 navtree.addItem(pointsItem);
		 navtree.addItem(groupItem);
		
	 westPanel = new DockLayoutPanel(Unit.EM);
	 loginLabel = new Label("Click to log in");
	 loginLabel.setStyleName("loginlabel");
	 westPanel.addNorth(loginLabel, 2);

	 helpLabel = new Label("User Guide");
	 helpLabel.setStyleName("loginlabel");
	 westPanel.addSouth(helpLabel, 2);
	 
//	 Button contactButton = new Button("Contact Admin");
//	 contactButton.addClickHandler(new ClickHandler(){
//		@Override
//		public void onClick(ClickEvent event) {
//			ContactBox cb  = new ContactBox(mrp);
//			cb.center(); cb.show();
//		}
//	 });
//	 westPanel.addSouth(contactButton, 3);
	 
	 DockLayoutPanel stdPanel = new DockLayoutPanel(Unit.PX);
	 stdPanel.addEast(sideTabPan, 90);
	 westPanel.addNorth(navtree,25);
	 westPanel.add(stdPanel);
	
	 
	 mP.addWest(westPanel, 13);
	 
	 tPanel = new TabLayoutPanel(0,Unit.EM);
	 mP.add(tPanel);
	 

	 
	 accountItem.setVisible(false);
	 
//	 event evt = new event(); evt.eid=17;
//	 PointsPage pp = new PointsPage(mrp,evt); pointspagelist.add(pp);
//	 tPanel.add(pp);
//	 navmap.put(eventItem.addItem("<font size=\"3\">Points</font>"), tPanel.getWidget(tPanel.getWidgetCount()-1));
//	 eventItem.setState(true);
	 
	 navtree.addSelectionHandler(new SelectionHandler<TreeItem>(){
		@Override
		public void onSelection(SelectionEvent<TreeItem> event) {
			boolean showtab = false;
			if(event.getSelectedItem() == pointsItem && navmap.get(pointsItem) == null){
				PointsTable pt = new PointsTable(mrp);
				tPanel.add(pt);
				navmap.put(pointsItem, tPanel.getWidget(tPanel.getWidgetCount()-1));
				renavmap.put(pt,pointsItem);
				navtree.setSelectedItem(null); navtree.setSelectedItem(pointsItem);
				tPanel.forceLayout();
			}
			if(event.getSelectedItem() == accountItem && navmap.get(accountItem) == null){
				AccountPage ap = new AccountPage(mrp,uname);
				tPanel.add(ap);
				navmap.put(accountItem, tPanel.getWidget(tPanel.getWidgetCount()-1));
				renavmap.put(ap, accountItem);
				navtree.setSelectedItem(null); navtree.setSelectedItem(accountItem);
			}
			
			if(event.getSelectedItem() == groupItem && navmap.get(groupItem) == null){
				GroupList gl = new GroupList(mrp);
				tPanel.add(gl);
				navmap.put(groupItem, tPanel.getWidget(tPanel.getWidgetCount()-1));
				renavmap.put(gl,groupItem);
				navtree.setSelectedItem(null); navtree.setSelectedItem(groupItem);
				tPanel.forceLayout();
			}
			
			if(navmap.get(event.getSelectedItem()) != null) {
				tPanel.selectTab(navmap.get(event.getSelectedItem()));
			}
			if(event.getSelectedItem() == eventItem){
				tPanel.forceLayout();
				if(navmap.get(eventItem) instanceof RaidCalendar){
					showtab = true;
					((RaidCalendar)navmap.get(eventItem)).cal.doLayout();
				}
				//((HasRedraw)navmap.get(eventItem)).Redraw();
			}
			sideTabPan.setVisible(showtab);
		}
 
	 });
	 
	 tPanel.addSelectionHandler(new SelectionHandler<Integer>() {
   	  //eEID raid
   	  //cal
   	  //ma my account
   	  //aNAME_CID account
   	  //points
   	  //pCID 
		 
		@Override
		public void onSelection(SelectionEvent<Integer> event) {
				String token = "";
				Widget w = tPanel.getWidget(event.getSelectedItem());
				if(w instanceof RaidCalendar || w instanceof EventTable){
					token = "cal";
				}
				else if(w instanceof PointsTable){
					token = "points";
				}
				else if(w instanceof GroupList){
					token = "gl";
				}
				else if(w instanceof AccountPage){
					AccountPage ap = ((AccountPage) w);
					if (ap.myacc == -1) History.newItem("ma");
					else{
						token = "a" + ap.name + "_" + Integer.toString(ap.myacc);
					}
				}
				else if(w instanceof PointsPage){
					token = "e" + Integer.toString(((PointsPage) w).evt.eid);
				}
				else if(w instanceof CharacterPointsTable){
					token = "p" + Integer.toString(((CharacterPointsTable) w).mchar.cid);
				}
				if(!token.equals("") && !token.equals(History.getToken())) {
					updatehist = true;
					History.newItem(token);
				}
		}
		 
	 });
	 
	 loginLabel.addClickHandler(new ClickHandler(){

		@Override
		public void onClick(ClickEvent event) {
			if(auth != AuthType.noauth) {
				auth = AuthType.noauth; 
				for(event ee : dataProvider.getList()){
					ee.attend = "";
				}
				if(cometClient != null) cometClient.stop();
				cometClient = null;
				rpsvc.Logout(authCallback);
				while(tablist.size() > permtabs) tablist.remove(tablist.size()-1);
				((HasRedraw)navmap.get(eventItem)).Redraw();
				if(currtab > permtabs -1){
					currtab = 0;
					 if(navmap.get(eventItem) instanceof RaidCalendar){
						 RaidCalendar trp = (RaidCalendar) navmap.get(eventItem);
						 trp.SetupTabs();
						 trp.tabbar.selectTab(currtab);
					 }
				}
				}
			else{
				AuthBox abox = new AuthBox(mrp);
				abox.center(); abox.show(); abox.textBox.setFocus(true);
			}
			//HandleAuthState();
		}
		 
		 
	 });
	 
	 helpLabel.addClickHandler(new ClickHandler(){

		@Override
		public void onClick(ClickEvent event) {
			if(helpWidget == null){
				tPanel.add(new HTML("<iframe height=\"100%\" width=\"100%\" frameBorder=\"0\" src=\"help/usage.html\"></iframe>"),"Help");
				helpWidget = tPanel.getWidget(tPanel.getWidgetCount()-1);
			}
			navtree.setSelectedItem(null);
			tPanel.selectTab(helpWidget);
			updatehist = true;
			History.newItem("help");
			rpsvc.AddHelpView(stringCallback);
		}
		 
	 });
	 
	 History.addValueChangeHandler(new ValueChangeHandler<String>() {
	      public void onValueChange(ValueChangeEvent<String> event) {
	    	  //eEID raid
	    	  //cal
	    	  //ma my account
	    	  //aNAME_CID account
	    	  //points
	    	  //pCID 
	    	  if(updatehist){
	    		  updatehist = false;
	    		  return;
	    	  }
	    	  String historyToken = event.getValue();
	    	  if(historyToken.length() < 2) return;
	    	  
	    	  if(historyToken.equals("swtor")){
	    		  if(navmap.get(eventItem) instanceof RaidCalendar){
	    				 RaidCalendar trp = (RaidCalendar) navmap.get(eventItem);
	    				 trp.tabbar.selectTab(1);
	    		  }
	    	  }
	    	  else if(historyToken.equals("wow")){
	    		  if(navmap.get(eventItem) instanceof RaidCalendar){
	    				 RaidCalendar trp = (RaidCalendar) navmap.get(eventItem);
	    				 trp.tabbar.selectTab(2);
	    		  }
	    	  }
	    	  else if(historyToken.equals("cal")){
	    		  navtree.setSelectedItem(null);
	    		  navtree.setSelectedItem(eventItem);
	    	  }
	    	  else if(historyToken.equals("ma")){
	    		  if(auth == AuthType.noauth) return; 
	   	    		 navtree.setSelectedItem(null);
	    		  navtree.setSelectedItem(accountItem);
	    	  }
	    	  else if(historyToken.equals("points")){
	    		  navtree.setSelectedItem(null);
	    		  navtree.setSelectedItem(pointsItem);
	    	  }
	    	  else if(historyToken.equals("gl")){
	    		  navtree.setSelectedItem(null);
	    		  navtree.setSelectedItem(groupItem);
	    	  }
	    	  else if(historyToken.equals("help")){
	    			if(helpWidget == null){
	    				tPanel.add(new HTML("<iframe height=\"100%\" width=\"100%\" frameBorder=\"0\" src=\"help/usage.html\"></iframe>"),"Help");
	    				helpWidget = tPanel.getWidget(tPanel.getWidgetCount()-1);
	    			}
	    			navtree.setSelectedItem(null);
	    			tPanel.selectTab(helpWidget);
	    	  }
	    	  else if(historyToken.startsWith("e") && isInteger(historyToken.substring(1))){
	    		  ViewPointsHist(Integer.parseInt(historyToken.substring(1)));
	    	  }
	    	  else if(historyToken.startsWith("a") && historyToken.contains("_")){
	    		  if(historyToken.charAt(historyToken.length() -1) == '_') return;
	    		  String name = historyToken.substring(1,historyToken.lastIndexOf("_"));
	    		  String cid = historyToken.substring(historyToken.lastIndexOf("_") + 1);
	    		  if(!isInteger(cid)) return;
	    		  ViewAccount(Integer.parseInt(cid),name);
	    	  }
	    	  else if(historyToken.startsWith("p") && isInteger(historyToken.substring(1))){
	    		  ViewCharHist(Integer.parseInt(historyToken.substring(1)));
	    	  }
	      
	      }
	     
	    });

	 
 
		tsComp = new Comparator<event>(){
			@Override
			public int compare(event arg0, event arg1) {
				return arg0.starttime.compareTo(arg1.starttime);
			}
		};
	 
		Timer checkAuth = new Timer(){

			@Override
			public void run() {
				rpsvc.GetSessionPerm(authCallback);	
			}

		};
		checkAuth.scheduleRepeating(120000);
	
	
		 
	 exportShowGroupInfo(mrp);
	 
	 if(History.getToken().equals("swtor")) starttab = 0;
	 else if(History.getToken().equals("wow")) starttab = 1;
	 
	 tablist.add("Raids:<>:Y:<>:N:<>:!:<>:!");
	 tablist.add("SWTOR:<>:Y:<>:N:<>:SWTOR:<>:!");
	 tablist.add("WoW:<>:Y:<>:N:<>:World of Warcraft:<>:!");
	 tablist.add("Other:<>:N:<>:Y:<>:!:<>:!");
	 permtabs = 4;
	 
		
	 Date dt = new Date();
	 rpsvc.GetTimeOffset(dt.getHours(), dt.getDate(), offsetCallback);
	 rpsvc.GetSessionPerm(authCallback);
	 
	 CalSwitch(true);

	
	 Timer chatTimer = new Timer(){

		@Override
		public void run() {
			PollChat();		
		}
		 
	 };
	 polllock = true;
	 rpsvc.PollChat(mpointer, pollCallback);
	 chatTimer.scheduleRepeating(30000);
	
 }//end init
 
 public void PollChat(){
	 if(polllock) return;
	 if(pointspagelist.size() == 0) return;
	 polllock = true;
	 rpsvc.PollChat(mpointer, pollCallback);
 }

 public void RemoveTab(TreeItem w){
	 if(navmap.get(w) != null){
		 tPanel.remove(navmap.get(w));
		 pointspagelist.remove(navmap.get(w));
		 charpagelist.remove(navmap.get(w));
		 accountlist.remove(navmap.get(w));
		 renavmap.remove(navmap.get(w));
		 navmap.remove(w);
		 
	 }

	 w.getParentItem().removeItem(w);
 }
 
 public void RemoveTabP(TreeItem w){
	 if(navmap.get(w) != null){
		 tPanel.remove(navmap.get(w));
		 pointspagelist.remove(navmap.get(w));
		 charpagelist.remove(navmap.get(w));
		 accountlist.remove(navmap.get(w));
		 renavmap.remove(navmap.get(w));
		 navmap.remove(w);
		 tPanel.selectTab(0);
	 }
 }
 
 public void RemoveTabId(int id){
	 Window.alert("hmmm");
	 TreeItem iditem = idmap.get("closeb"+id);
	 idmap.remove("closeb"+id);
	 RemoveTab(iditem);
 }
 
 public void ViewPointsHist(int eid){
	 for(event e : dataProvider.getList()){
		 if(e.eid == eid) {
			 ViewPoints(e);
			 return;
		 }
	 }
	 return;
 }
 
 public void ViewPoints(event evt){
	 for(PointsPage tpp : pointspagelist){
		 if(tpp.evt.eid == evt.eid){
			 navtree.setSelectedItem(null);
			 TreeItem pitem = renavmap.get(tpp);
			 tPanel.selectTab(navmap.get(pitem));
			 navtree.setSelectedItem(pitem);
			 return;
		 }
	 }
	 PointsPage pp = new PointsPage(mrp,evt); pointspagelist.add(pp);
	 tPanel.add(pp);
	// String divid = "closeb" + idcount;
	 TreeItem pitem;
	 if(evt.game.equals("")) pitem = eventItem.addItem("<font size=\"2\">" + evt.note.split(":;:")[0] + " " + evt.starttime.getDate() + "</font>");
	 else pitem = eventItem.addItem("<font size=\"2\">" + evt.dest + " " + evt.starttime.getDate() + "</font>");
	// TreeItem pitem = eventItem.addItem("<div onmouseover=showx(\"" + divid + "\") onmouseout=hidex(\"" + divid + "\")><font size=\"2\">"
	//		 + evt.dest + " " + evt.starttime.getDate() + "<div id=\"" + divid + "\" style=\"display: none\"><img src=\"icons/close.png\"></div><font></div>");
	// SetOC(idcount,divid,mrp);	 
	// idmap.put(divid, pitem);
	// idcount++;
	 navmap.put(pitem, tPanel.getWidget(tPanel.getWidgetCount()-1));
	 renavmap.put(pp, pitem);
	 tPanel.selectTab(navmap.get(pitem));
	 eventItem.setState(true);
	 navtree.setSelectedItem(null);
	 navtree.setSelectedItem(pitem);
	 tPanel.forceLayout();
 }
 
 public void CalSwitch(boolean showcal){
	 RemoveTabP(eventItem);
	
	 if(!showcal){
	 EventTable eTable = new EventTable(mrp);
	 eTable.setSize("100%", "100%");
	 tPanel.add(eTable);
	 eTable.setSize("100%", "100%");
	 navmap.put(eventItem, tPanel.getWidget(tPanel.getWidgetCount()-1));
	 }
	 else{
		 RaidCalendar rcal = new RaidCalendar(mrp);
		 tPanel.add(rcal);
		 rcal.SetupCal();
	     navmap.put(eventItem, tPanel.getWidget(tPanel.getWidgetCount()-1));
	 }
	 navtree.setSelectedItem(null); navtree.setSelectedItem(eventItem);
	 ((HasRedraw) navmap.get(eventItem)).HandleAuthChange(auth);
	 if(dataProvider.getList().size() == 0) GetEvents();
	 else if(showcal) ((HasRedraw) navmap.get(eventItem)).HandleEvents();
	 tPanel.forceLayout();
 }
 
 public void ViewCharHist(int cid){
	 for(CharacterPointsTable tpp : charpagelist){
		 if(tpp.mchar.cid == cid){
			 tpp.UpdatePoints();
			 navtree.setSelectedItem(null);
			 TreeItem pitem = renavmap.get(tpp);
			 tPanel.selectTab(navmap.get(pitem));
			 navtree.setSelectedItem(pitem);
			 return;
		 }
	 }
	 AsyncCallback<character> charCallback = new AsyncCallback<character>(){

		@Override
		public void onFailure(Throwable caught) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onSuccess(character result) {
			ViewChar(result);			
		}
		 
	 };
	 rpsvc.GetCharacter(cid, charCallback);
 }
 
 public void ViewChar(character mchar){
	 ViewChar(mchar,-1);
 }
 
 public void ViewChar(character mchar,int poolid){
	 
	 for(CharacterPointsTable tpp : charpagelist){
		 if(tpp.mchar.cid == mchar.cid){
			 tpp.UpdatePoints();
			 navtree.setSelectedItem(null);
			 TreeItem pitem = renavmap.get(tpp);
			 tPanel.selectTab(navmap.get(pitem));
			 navtree.setSelectedItem(pitem);
			 return;
		 }
	 }
	 CharacterPointsTable pp = new CharacterPointsTable(mrp,mchar,poolid); charpagelist.add(pp);
	 tPanel.add(pp);
	 TreeItem pitem = pointsItem.addItem("<font size=\"2\">" + mchar.name +"</font>");
	 navmap.put(pitem, tPanel.getWidget(tPanel.getWidgetCount()-1));
	 renavmap.put(pp, pitem);
	 tPanel.selectTab(navmap.get(pitem));
	 pointsItem.setState(true);
	 navtree.setSelectedItem(null);
	 navtree.setSelectedItem(pitem);
	 tPanel.forceLayout();
 }
 
 public void ViewAccount(int cid, String name){
	 if(auth == AuthType.noauth) return; 
	for(AccountPage ap : accountlist){
		if(ap.myacc == cid){
			navtree.setSelectedItem(null);
			TreeItem pitem = renavmap.get(ap);
			tPanel.selectTab(navmap.get(pitem));
			navtree.setSelectedItem(pitem);
			return;
		}
	}
	AccountPage ap = new AccountPage(mrp,name,cid); accountlist.add(ap);
	tPanel.add(ap);
	TreeItem pitem = accountItem.addItem("<font size=\"2\">" + name +"</font>");
	navmap.put(pitem, tPanel.getWidget(tPanel.getWidgetCount()-1));
	renavmap.put(ap, pitem);
	tPanel.selectTab(navmap.get(pitem));
	accountItem.setState(true);
	navtree.setSelectedItem(null);
	navtree.setSelectedItem(pitem);
	tPanel.forceLayout();
	
 }
 
 public interface HasRedraw{
	 public void Redraw();
	 public void HandleAuthChange(AuthType atype);
	 public void HandleEvents();
	 public void AddEvent(event evt);
	 public event GetEvent(int eid);
 }
 
 
 public void HandleAuthState(){
	 switch(auth){
	 	case admin:
	 		loginLabel.setText("Logged in as " + uname + " (admin)");
	 		accountItem.setVisible(true);
	 		break;
	 	case cl:
	 		loginLabel.setText("Logged in as " + uname + " (CL)");
	 		accountItem.setVisible(true);
	 		break;
	 	case user:
	 		loginLabel.setText("Logged in as " + uname);
	 		accountItem.setVisible(true);
	 		break;
		 default:
			 loginLabel.setText("Click to log in");
			 accountItem.setVisible(false);
			 uid = -1;
			 RemoveTabP(accountItem);
			 //tPanel.selectTab(0);
			 break;
	 }
	 ((HasRedraw) navmap.get(eventItem)).HandleAuthChange(auth);
	 if(navmap.get(eventItem) instanceof RaidCalendar){
		 RaidCalendar trp = (RaidCalendar) navmap.get(eventItem);
		 trp.SetupTabs();
		 String htoken = History.getToken();
		 if(starttab == 0 || starttab == 1){
			 currtab = starttab;
			 starttab = -1;
		 }
		 trp.tabbar.selectTab(currtab);
	 }
	 for(int i = 0; i < pointspagelist.size(); i++) pointspagelist.get(i).HandleAuthChange(auth);
	 for(int i = 0; i < charpagelist.size(); i++) charpagelist.get(i).HandleAuthChange(auth);
 }
 
public void GetEvents(){
		AsyncCallback<ArrayList<event>> eventCallback = new AsyncCallback<ArrayList<event>>(){

			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onSuccess(ArrayList<event> result) {
				dataProvider.getList().clear();
				dataProvider.getList().addAll(result);
				Collections.sort(dataProvider.getList(),tsComp);
				Collections.reverse(dataProvider.getList());
				((HasRedraw) navmap.get(eventItem)).HandleEvents();
			}
			
		};
		
		rpsvc.GetEventList(eventCallback);
	}
 

 public void SetupCallbacks(){
	 authCallback = new AsyncCallback<String>(){

		@Override
		public void onFailure(Throwable caught) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onSuccess(String result) {
			String[] split = result.split(",");
			if(split.length > 1){
			if(split[0].equals("admin")) auth = AuthType.admin;
			else if(split[0].equals("cl")) auth = AuthType.cl;
			else if(split[0].equals("user")) auth = AuthType.user;
			else {auth = AuthType.noauth;}
			uname = split[1];
			uid = Integer.parseInt(split[2]);
			calheight = Integer.parseInt(split[3]);
			mil = (Integer.parseInt(split[4]) == 0 ? true : false);
			String tabs = split[5];
			if(tabs == null) tabs = "";
			if(tabs.length() > 0 && !tabs.equals("!")){
				currtab = Integer.parseInt(tabs.substring(0,1));
				if(tabs.length() > 1){
					while(tablist.size() > permtabs) tablist.remove(tablist.size()-1);
					String[] tlist = tabs.substring(1).split(":;:");
					for(int i = 0; i < tlist.length; i++) tablist.add(tlist[i]);
				}
			}
			if(navmap.get(accountItem) == null){
				AccountPage ap = new AccountPage(mrp,uname);
				int i  = tPanel.getSelectedIndex();
				tPanel.add(ap);
				navmap.put(accountItem, tPanel.getWidget(tPanel.getWidgetCount()-1));
				renavmap.put(ap, accountItem);
				//tPanel.selectTab(i);
			}
			
			}
			else {
				auth = AuthType.noauth; 
				uname = "";
				if(jli) Window.alert("Invalid user/pass");
			}
			
			jli = false;

//			if(auth != AuthType.noauth){
//			CometSerializer serializer = GWT.create(ChatCometSerializer.class);
//			cometClient = new CometClient(GWT.getHostPageBaseURL() + "servlet/comet", serializer, new CometListener() {
//
//				@Override
//				public void onConnected(int heartbeat) {
//					// TODO Auto-generated method stub
//					
//				}
//
//				@Override
//				public void onDisconnected() {
//					// TODO Auto-generated method stub
//					
//				}
//
//				@Override
//				public void onError(Throwable exception, boolean connected) {
//					// TODO Auto-generated method stub
//					
//				}
//
//				@Override
//				public void onHeartbeat() {
//					// TODO Auto-generated method stub
//					
//				}
//
//				@Override
//				public void onRefresh() {
//					// TODO Auto-generated method stub
//					
//				}
//
//				@Override
//				public void onMessage(List<? extends Serializable> messages) {
//					for(Serializable m : messages){
//						String[] split = ((String) m).split(":;:");
//						if(split.length < 2) return;
//						int eid = Integer.parseInt(split[0]);
//						
//						for(PointsPage p: pointspagelist){
//							if(p.evt.eid == eid){
//								p.AddMessage(split[1]);
//								break;
//							}
//						}
//					}
//					
//				}
//				
//			});
//			cometClient.start();
//			}
			
			HandleAuthState();
//			if(firstload && !lasthist.equals("")){
//				History.newItem(lasthist);
//				firstload = false;
//			}
		}
		 
	 };
	 
	 pollCallback = new AsyncCallback<ArrayList<String>>(){

		@Override
		public void onFailure(Throwable caught) {
			polllock = false;			
		}

		@Override
		public void onSuccess(ArrayList<String> result) {
			polllock = false;
			if(result == null) return;
			mpointer = Integer.parseInt(result.get(0));

		//	GWT.log(Integer.toString(result.size()) + " " + Integer.toString(mpointer));
			for(int i = 1; i < result.size(); i++){
				String[] split = result.get(i).split(":;:");
				if(split.length < 2) return;
				int eid = Integer.parseInt(split[0]);
				
				for(PointsPage p: pointspagelist){
					if(p.evt.eid == eid){
						p.AddMessage(split[1]);
						break;
					}
				}
			}
		}
		 
	 };
	 
	 destCallback = new AsyncCallback<String>(){

		@Override
		public void onFailure(Throwable caught) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onSuccess(String result) {
			//game1,id,dest1,dest2,...:::game2,id,dest1,dest2,...			
			destlist = new HashMap<String,ArrayList<String>>();
			String[] games = result.split(":::");
			for(int i = 0; i < games.length; i++){
				String[] dest = games[i].split(",");
				ArrayList<String> dlist = new ArrayList<String>();
				for(int j = 1; j < dest.length; j++){
					dlist.add(dest[j]);
				}
				destlist.put(dest[0], dlist);
			}
		}
		 
	 };
	 
	 stringCallback = new AsyncCallback<String>(){

		@Override
		public void onFailure(Throwable caught) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onSuccess(String result) {
			// TODO Auto-generated method stub

		}
		 
	 };
	 
	 alertCallback = new AsyncCallback<String>(){

		@Override
		public void onFailure(Throwable caught) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onSuccess(String result) {
			Window.alert(result);
		}
		 
	 };
	 
	 offsetCallback = new AsyncCallback<Integer>(){

		@Override
		public void onFailure(Throwable caught) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onSuccess(Integer result) {
			timeos = result;			
		}
		 
	 };
 }
 
 	public void UpdateTabs(){
 		StringBuilder sb = new StringBuilder();
 		sb.append(currtab);
 		for(int i = permtabs; i < tablist.size(); i++){
 			sb.append((i > permtabs ? ":;:" : "") + tablist.get(i));
 		}
 		rpsvc.SetTab(sb.toString(), stringCallback);
 	}
 
	public native void GetPointsList() /*-{
		$wnd.open('servlet/points','target=_blank');
	}-*/;
	
	public native void SetOC(int id, String sid, RaidPoints rp) /*-{
		var ele = $doc.getElementById(sid);
		ele.onclick = function(){
			rp.@com.raidpoints.client.RaidPoints::RemoveTabId(I)(id);
		}
	}-*/;
	
	public native void exportShowGroupInfo(RaidPoints rp) /*-{
		$wnd.showgroupinfo = function(gid) {
			rp.@com.raidpoints.client.RaidPoints::ShowGroupInfo(I)(gid);
		}
	}-*/;
	
	public void ShowGroupInfo(int gid){
		GroupList.GroupInfoBox gib = new GroupList.GroupInfoBox(gid, mrp);
		gib.center(); gib.show();
	}
	
 public static enum AuthType{
	 noauth,user,admin,cl,creator
 }
 
public boolean isInteger( String input )  
	{  
		try  
		{  
			Integer.parseInt( input );  
			return true;  
		}  
		catch( Exception e)  
		{  
			return false;  
		}  
	}
 
 public static String GetCicon(character c){
	 if(c.gid == 1 || c.game.equals("World of Warcraft")){
		 return (c.Class == null ? "mage" : c.Class.toLowerCase().replace(" ", "") );
	 }
	 else if(c.gid == 2 || c.game.equals("SWTOR")){
		 if(c.Class == null) return "swtorjediknight";
		 else if(c.Class.equals("Jedi Sage") || c.Class.equals("Jedi Shadow")) return "swtorjediconsular";
		 else if(c.Class.equals("Jedi Guardian") || c.Class.equals("Jedi Sentinel")) return "swtorjediknight";
		 else if(c.Class.equals("Gunslinger") || c.Class.equals("Scoundrel")) return "swtorsmuggler";
		 else if(c.Class.equals("Commando") || c.Class.equals("Vanguard")) return "swtortrooper";
		 else if(c.Class.equals("Mercenary") || c.Class.equals("Powertech")) return "swtorbountyhunter";
		 else if(c.Class.equals("Operative") || c.Class.equals("Sniper")) return "swtoragent";
		 else if(c.Class.equals("Sith Assassin") || c.Class.equals("Sith Sorcerer")) return "swtorsithinquisitor";
		 else if(c.Class.equals("Sith Juggernaut") || c.Class.equals("Sith Marauder")) return "swtorsithwarrior";
		 else return "swtorjediknight";
	 }
	 else if(c.gid == 5 || c.game.equals("Rift")){
		 if(c.Class == null) return "riftwarrior";
		 else return "rift" + c.Class.toLowerCase();
	 }
	 else{
		 return "";
	 }
 }

}
